using System;
using System.Collections.Generic;
using Wamm.ApplicationExceptions;
using Wamm.Model.Entities;

namespace Wamm.Model.Validation {
    public class ValidatePerson {

        // Error messages
        public const string FIRST_NAME_IS_REQUIRED = "First Name is required";
        public const string LAST_NAME_IS_REQUIRED = "Last Name is required";
        public const string GENDER_MUST_BE_M_OR_F = "Gender must be M or F";
        public const string INVALID_DATE = "Invalid date";
        public const string INVALID_BIRTHDATE = "Birthdate is invalid";

        public static readonly int ValidBirthdateOffset = 200;

        public static void Validate(Person person, IList<RuleViolation> errors) {

            var personErrors = new RuleViolationFor<Person>(errors);//RulesViolationFor<Person>(errors); ;

            ValidateFirstName(personErrors, person);

            ValidateLastName(personErrors, person);

            ValidateGender(personErrors, person);

            ValidateBirthDate(personErrors, person);
         }

        private static void ValidateGender(RuleViolationFor<Person> errors, Person person) {
            if (person.Gender != null) {
                if ((person.Gender != Person.Male) &&
                    (person.Gender != Person.Female)) {
                        errors.ErrorFor(x => x.Gender, GENDER_MUST_BE_M_OR_F);
                }
            }
        }

        private static void ValidateLastName(RuleViolationFor<Person> errors, Person person) {
            if (string.IsNullOrWhiteSpace(person.LastName)) {
                errors.ErrorFor(x => x.LastName, LAST_NAME_IS_REQUIRED);
            }
        }

        private static void ValidateFirstName(RuleViolationFor<Person> errors, Person person) {
            if (string.IsNullOrWhiteSpace(person.FirstName)) {
                errors.ErrorFor(x => x.FirstName, FIRST_NAME_IS_REQUIRED);
            }
        }

        private static void ValidateBirthDate(RuleViolationFor<Person> errors, Person person) {

            if (person.BirthDate != null) {
                if (person.BirthDate > DateTime.Now.AddYears(ValidBirthdateOffset)) {
                    errors.ErrorFor(x => x.BirthDate, INVALID_BIRTHDATE);
                }

                if (person.BirthDate < DateTime.Now.AddYears(ValidBirthdateOffset * -1)) {
                    errors.ErrorFor(x => x.BirthDate, INVALID_BIRTHDATE);
                }
            }
        }
    }
}